package com.gxar.quick.ar.server.base.common.utils;

import com.gxar.common.utils.StringUtils;
import com.gxar.quick.ar.server.base.common.constant.ArProtocolConstant;
import com.gxar.quick.ar.server.base.common.constant.WechatPayConstant;
import com.gxar.quick.ar.server.base.config.WechatPaySdkConfig;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.cipher.Signer;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author nice
 * @version 1.0
 * @created 2023/11/11.
 */
public class AesUtils {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;

    public static String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException, IOException {
        try {
            byte[] aesKey = WechatPayConstant.API_V3_KEY.getBytes();
            if (aesKey.length != KEY_LENGTH_BYTE) {
                throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
            }
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);
            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static String getSignWithConfig(String appId, long timestamp, String nonceStr, String body) {
        String message = buildMessage(appId, timestamp, nonceStr, body);
        String signature = null;
        try {
            Config config = WechatPaySdkConfig.getConfig();
            Signer signer = config.createSigner();
            signature = signer.sign(message).getSign();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return signature;
    }

    private static String buildMessage(String appId, long timestamp, String nonceStr, String body) {
        return appId + "\n" + timestamp + "\n" + nonceStr + "\n" + body + "\n";
    }

    /**
     * AR配置内容加密
     *
     * @param plainText 配置内容
     * @return
     */
    public static String encryptArConfig(String plainText) {
        if (StringUtils.isEmpty(plainText)) {
            return plainText;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(ArProtocolConstant.AR_CONFIG_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec spec = new IvParameterSpec(ArProtocolConstant.AR_CONFIG_IV.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.ENCRYPT_MODE, key, spec);
            byte[] encrypted = cipher.doFinal(plainText.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException |
                 BadPaddingException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
